package com.xnck.ifpms.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.xiaoleilu.hutool.StrUtil;
import com.xnck.ifpms.annotation.AuthenPassport;
import com.xnck.ifpms.utils.ContextUtils;
import com.xnck.ifpms.utils.SessionUtils;

/**
 * 登录拦截器
 * @author zhangmengliang
 *
 */
public class LoginInterceptor  extends HandlerInterceptorAdapter{
	protected static final Logger logger = Logger.getLogger(LoginInterceptor.class);
	
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        
    }
 
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView view) throws Exception {

    }
   
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	//如果拦截的是方法，查验是否有AuthenPassport注解，如果有注解则需要验证用户是否已登录
    	if (handler instanceof HandlerMethod) {
    		HandlerMethod method = (HandlerMethod)handler;
        	AuthenPassport authPassport = method.getMethodAnnotation(AuthenPassport.class);
        	if (authPassport == null || authPassport.validate() == false) {
    			return true;
    		}
        	String userId;
        	try {
        		 userId = SessionUtils.getCurrentUserId(request);
			} catch (Exception e) {
				logger.error(e.toString());
				userId = null;
			}
        	if (StrUtil.isNotBlank(userId)) {
				return true;
			}
        	ContextUtils.respString(response, "未登录");
        	return false;
		}
    	return true;
    }
}
